<template>
  <header class="header google-anno-skip">
    <div class="container">
      <div class="header-content">

        <!-- Mobile Menu Button -->
        <button class="menu-toggle" @click="handleMenuToggle">
          <span class="menu-icon"></span>
        </button>

        <!-- Navigation Menu -->
        <nav class="nav-menu">
          <ul>
            <li>
              <!-- <a :href="`/top-rank/${window?.location.search}`">
                TOP RANK
              </a> -->
              <div @click="handleTopRank(urls.topRank)" class="nav-menu-item">
                  TOP RANK
              </div>
            </li>
            <li>
              <div @click="handleTopRank(urls.apps)" class="nav-menu-item">
                APPS
              </div>
            </li>
            <li>
              <div @click="handleTopRank(urls.games)" class="nav-menu-item">
                GAMES
              </div>
            </li>
          </ul>
        </nav>
        
        <!-- Logo -->
        <div @click="handleTopRank(urls.home)" class="logo">APKPICK</div>

        <!-- Search Bar -->
        <div class="search-container">
          <input
            type="text"
            placeholder="search any applications"
            class="search-input"
            v-model="searchQuery"
            required
            @keyup.enter="handleSearch()"
          >
          <el-button class="search-button" @click="handleIcon">
            <el-icon><Search /></el-icon>
          </el-button>
        </div>

        <!-- Search Drawer -->
        <el-drawer
          v-model="isSearchOpen"
          direction="rtl"
          size="100%"
          :with-header="false"
          class="search-drawer"
        >
          <div class="search-drawer-content">
            <div class="search-drawer-header">
              <div class="close-button" @click="isSearchOpen = false">
                <el-icon><CloseBold /></el-icon>
              </div>
            </div>
            <div class="search-drawer-body">
              <div class="search-input-container">
                <input type="text" placeholder="search any applications" class="search-input-mobile" v-model="searchQuery" @keyup.enter="handleSearchMobile()">
                <button class="search-button-mobile" @click="handleSearchMobile()">
                  <el-icon><Search /></el-icon>
                </button>
              </div>
              <div class="trending-searches">
                <h3>Trending Searches</h3>
                <div class="search-tags">
                  <span class="search-tag" @click="handleTag('chat')">chat</span>
                  <span class="search-tag" @click="handleTag('game')">game</span>
                  <span class="search-tag" @click="handleTag('Face')">Face</span>
                  <span class="search-tag" @click="handleTag('tiktok')">tiktok</span>
                </div>
              </div>
              <div class="top-downloads">
                <div class="section-header">
                  <h3>Top Downloads</h3>
                  <a href="/top-rank" class="see-all">See all <el-icon><ArrowRight /></el-icon></a>
                </div>
                <div class="app-list">
                  <a :href="getDetailUrl(app)" class="app-item" v-for="app in topApps" :key="app.name">
                    <img :src="app.icon" :alt="app.name">
                    <div class="app-info">
                      <div class="app-name">{{ app.name }}</div>
                      <div class="app-rating">
                        {{ app.rating }}
                        <div class="icon">★</div>
                      </div>
                    </div>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </el-drawer>

        <!-- Mobile Menu Drawer -->
        <el-drawer
          v-model="isMenuOpen"
          direction="ltr"
          size="75%"
          :with-header="false"
          class="mobile-drawer"
        >
          <div class="mobile-menu-content">
            <div class="mobile-header">
              <div class="close-button" @click="isMenuOpen = false">
                <el-icon><CloseBold /></el-icon>
              </div>
              <div class="mobile-logo">APKPICK</div>
            </div>
            <ul class="mobile-menu-list">
              <li class="mobile-menu-item">
                <a :href="urls.home" class="mobile-menu-link">
                  <el-icon><HomeFilled /></el-icon>
                  Home
                </a>
              </li>
              <li class="mobile-menu-item">
                <a :href="urls.topRank" class="mobile-menu-link">
                  <el-icon><Histogram /></el-icon>
                  TOP RANK
                </a>
              </li>
              <li class="mobile-menu-item">
                <a class="mobile-menu-link" @click.prevent="toggleSubmenu('mobile-apps')">
                  <svg-icon name="apps" class="menu-icon-svg" />
                  APPS
                  <el-icon class="arrow" :class="{ 'is-active': activeSubmenu === 'mobile-apps' }">
                    <ArrowDown />
                  </el-icon>
                </a>
                <ul class="mobile-submenu" v-show="activeSubmenu === 'mobile-apps'"
                    v-bind="containerProps"
                    style="max-height: 60vh; overflow-y: auto;">
                  <div v-bind="wrapperProps">
                    <li v-for="item in appCategories" :key="item.path">
                      <a :href="urls.categoryUrls.get(`apps-${item.slug}`)">{{ item.name }}</a>
                    </li>
                  </div>
                </ul>
              </li>
              <li class="mobile-menu-item">
                <a class="mobile-menu-link" @click.prevent="toggleSubmenu('mobile-games')">
                  <svg-icon name="games" class="menu-icon-svg" />
                  GAMES
                  <el-icon class="arrow" :class="{ 'is-active': activeSubmenu === 'mobile-games' }">
                    <ArrowDown />
                  </el-icon>
                </a>
                <ul class="mobile-submenu" v-show="activeSubmenu === 'mobile-games'"
                    v-bind="containerProps"
                    style="max-height: 60vh; overflow-y: auto;">
                  <div v-bind="wrapperProps">
                    <li v-for="item in gameCategories" :key="item.path">
                      <a :href="urls.categoryUrls.get(`games-${item.slug}`)">{{ item.name }}</a>
                    </li>
                  </div>
                </ul>
              </li>
            </ul>
          </div>
        </el-drawer>
      </div>
    </div>
  </header>
</template>

<script setup>
import topDownloadData from '~/assets/data/top/top_downloads.json'
import appCategoriesData from '~/assets/data/categories/app_categories.json'
import gameCategoriesData from '~/assets/data/categories/game_categories.json'
import { homeParams } from '~/utils/homeParams'

const router = useRouter()
const isMenuOpen = ref(false)
const isSearchOpen = ref(false)
const searchQuery = ref('')
const activeSubmenu = ref('')

// 存储所有生成的 URL
const urls = ref({
  topRank: '',
  apps: '',
  games: '',
  home: '',
  search: '',
  categoryUrls: new Map()
})

const generateUrls = () => {
  if (!process.client) return

  // 生成基础 URL
  const baseParams = homeParams()
  const searchParams = new URLSearchParams(baseParams).toString()
  
  // 生成各个页面的 URL
  urls.value.topRank = `/top-rank?${searchParams}`
  urls.value.apps = `/apps?${searchParams}`
  urls.value.games = `/games?${searchParams}`
  urls.value.home = `/?${searchParams}`
  
  // 生成分类 URL
  appCategoriesData.forEach(item => {
    const queryParams = {
      type: 'apps',
      name: encodeURIComponent(item.name),
      ...baseParams
    }
    urls.value.categoryUrls.set(`apps-${item.slug}`, `/categories/${item.slug}?${new URLSearchParams(queryParams).toString()}`)
  })

  gameCategoriesData.forEach(item => {
    const queryParams = {
      type: 'games',
      name: encodeURIComponent(item.name),
      ...baseParams
    }
    urls.value.categoryUrls.set(`games-${item.slug}`, `/categories/${item.slug}?${new URLSearchParams(queryParams).toString()}`)
  })
}

const isMobile = computed(() => {
  if (typeof window !== 'undefined') {
    return window.innerWidth <= 768
  }
  return false
})

if (typeof window !== 'undefined') {
  window.addEventListener('resize', () => {
    if (!isMobile.value && isSearchOpen.value) {
      isSearchOpen.value = false
    }
  })
}

const topApps = computed(() => {
  return topDownloadData.slice(0, 6)
})

const appCategories = computed(() => {
  return appCategoriesData
})

const gameCategories = computed(() => {
  return gameCategoriesData
})

const getDetailUrl = (item) => {
  const queryParams = {
    type: 'apps',
    slug: item.slug,
    ...homeParams()
  }
  return `/details?${new URLSearchParams(queryParams).toString()}`
}

const toggleSubmenu = (menu) => {
  activeSubmenu.value = activeSubmenu.value === menu ? '' : menu
}

const handleSearch = (tag) => {
  if (!searchQuery.value.trim() && !tag) return
  
  const queryParams = {
    name: tag || searchQuery.value.trim(),
    ...homeParams()
  }
  window.location.href = `/search?${new URLSearchParams(queryParams).toString()}`
}

const handleTag = (tag) => {
  console.log('handleTag');
  
  handleSearch(tag)
}

// 移动端搜索按钮
const handleIcon = () => {
  if (isMobile.value) {
    isSearchOpen.value = true
    logEvent('App_Search_Page_Show')
  } else {
    if (searchQuery.value.trim()) {
      handleSearch()
    }
  }
}

// 移动端弹框里搜索
const handleSearchMobile = () => {
  console.log('handleSearchMobile');
  
  if (searchQuery.value.trim()) {
    isSearchOpen.value = false
    handleSearch()
  }
}

// 打开移动端侧边栏
const handleMenuToggle = () => {
  if (isMobile.value) {
    isMenuOpen.value = true
    logEvent('App_Sidebar_Page_Show')
  }
}

// 在组件挂载后生成所有 URL
onMounted(() => {
  generateUrls()
  
  const homeParams = window?.location.search.split('?')[1]
  const sessionParams = sessionStorage.getItem('search')
  const currentPath = router.currentRoute.value.path
  
  if (!!homeParams && sessionParams !== homeParams && currentPath === '/') {
    sessionStorage.setItem('search', homeParams)
  }
})

const handleTopRank = (link) => {
  window.location.href = link
}
</script>

<style scoped lang="scss">
.el-icon {
  padding: 0;
  font-size: 1.4rem;
  height: 1rem;
  widows: 1rem;
}
.header {
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 1rem;
  }

  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    position: relative;
  }

  .logo {
    font-size: 1.5rem;
    font-weight: bold;
    color: #F78B17;
    text-decoration: none;
    cursor: pointer;
  }

  .nav-menu {
    ul {
      display: flex;
      list-style: none;
      margin: 0;
      padding: 0;
      gap: 2rem;
    }

    li {
      position: relative;
    }

    .nav-menu-item {
      color: #111111;
      text-decoration: none;
      font-size: 0.9rem;
      font-weight: 500;
      transition: color 0.3s;
      display: flex;
      align-items: center;
      gap: 0.75rem;
      cursor: pointer;

      .menu-icon-svg {
        color: #F78B17;
      }

      &:hover {
        color: #F78B17;
      }

      .arrow {
        transition: transform 0.3s;
        color: #333;
      }

      &.active .arrow {
        transform: rotate(180deg);
        color: #F78B17;
      }
    }

    .submenu {
      position: absolute;
      top: 100%;
      left: 0;
      background: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      padding: 0.5rem 0;
      min-width: 200px;
      z-index: 1000;

      li {
        display: block;
      }

      a {
        padding: 0.5rem 1rem;
        font-size: 0.9rem;
        display: block;
        white-space: nowrap;

        &:hover {
          background: #f5f5f5;
        }
      }
    }

    @media (max-width: 768px) {
      display: none;
    }
  }

  .search-container {
    display: flex;
    align-items: center;
    border: 1px solid #f78b17;
    border-radius: 20px;
    padding: 0.2rem 1rem;
    background: #f5f5f5;
    @media screen and (max-width: 768px) {
      background-color: #fff;
    }
    .search-input {
      border: none;
      outline: none;
      width: 200px;
      font-size: 0.9rem;
      background: transparent;
    }

    .search-button {
      background: none;
      border: none;
      cursor: pointer;
      padding: 0;
      margin-left: 0.5rem;
      display: flex;
      align-items: center;
      color: #f78b17;
    }

    .search-icon {
      display: inline-block;
      width: 16px;
      height: 16px;
      border: 2px solid #666;
      border-radius: 50%;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        width: 2px;
        height: 8px;
        background: #666;
        bottom: -6px;
        right: -6px;
        transform: rotate(45deg);
      }
    }
  }

  .menu-toggle {
    display: none;
    background: none;
    border: none;
    cursor: pointer;
  }

  .menu-icon {
    display: block;
    width: 18px;
    height: 2px;
    background: #333;
    position: relative;

    &::before,
    &::after {
      content: '';
      position: absolute;
      width: 24px;
      height: 2px;
      background: #333;
      left: 0;
    }

    &::before {
      top: -6px;
    }

    &::after {
      bottom: -6px;
    }
  }

  @media (max-width: 768px) {
    .menu-toggle {
      display: block;
      order: 1;
    }

    .logo {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      order: 2;
    }

    .search-container {
      display: block;
      order: 3;
      border: none;
      padding: 0;

      .search-input {
        display: none;
      }
    }

    :deep(.el-drawer) {
      .el-drawer__body {
        padding: 10px 20px;
      }
    }

    .mobile-menu-content {
      .mobile-header {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        margin-bottom: 1rem;
        .close-button {
          cursor: pointer;
          padding: 0.5rem;
          border: none;
          background: none;
          position: absolute;
          left: 0;
          top: 0;
        }
        .mobile-logo {
          /* display: flex;
          justify-content: center; */
          font-size: 1.5rem;
          font-weight: bold;
          color: #F78B17;
        }
      }

      .mobile-menu-list {
        list-style: none;
        padding: 0;
        margin: 0;

        .mobile-menu-item {
          /* border-bottom: 1px solid #eee; */
          .el-icon {
            color: #F78B17;
          }
        }

        .mobile-menu-link {
          padding: .8rem .2rem;
          font-size: 1rem;
          display: flex;
          align-items: center;
          gap: 0.75rem;
          color: #333;
          text-decoration: none;
          position: relative;

          .menu-icon-svg {
            color: #F78B17;
          }

          &:hover {
            color: #F78B17;
          }

          .arrow {
            transition: transform 0.3s;
            margin-left: auto;
            color: #333;
            
            &.is-active {
              transform: rotate(180deg);
              color: #F78B17;
            }
          }
        }
      }
    }
  }
}

.mobile-menu-content {
  .mobile-menu-list {
    .mobile-menu-link {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      padding: .8rem .2rem;
      font-size: 1rem;
      color: #333;
      text-decoration: none;
      position: relative;

      .menu-icon-svg {
        color: #F78B17;
      }

      &:hover {
        color: #F78B17;
      }

      .arrow {
        transition: transform 0.3s;
        margin-left: auto;
        color: #333;
        
        &.is-active {
          transform: rotate(180deg);
          color: #F78B17;
        }
      }
    }

    .mobile-submenu {
      padding-left: 1rem;
      list-style: none;
      
      li {
        a {
          padding: 0.5rem 1rem;
          display: block;
          color: #666666;
          text-decoration: none;
          font-size: 0.9rem;
          
          &:hover {
            color: #F78B17;
          }
        }
      }
    }
  }
}

.menu-icon-svg {
  width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  
  :deep(svg) {
    width: 100%;
    height: 100%;
  }
}

.submenu, .mobile-submenu {
  scrollbar-width: thin;
  scrollbar-color: #F78B17 #f5f5f5;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f5f5f5;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: #F78B17;
    border-radius: 3px;
  }
}

.mobile-submenu {
  transition: max-height 0.3s ease-in-out;
}

.search-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
  }
}

.search-drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;

  .search-drawer-header {
    padding: 1rem;
    display: flex;
    align-items: center;

    .close-button {
      cursor: pointer;
      padding: 0.5rem;
      
      :deep(svg) {
        width: 20px;
        height: 20px;
      }
    }
  }

  .search-drawer-body {
    flex: 1;
    /* padding: 1rem; */
    overflow-y: auto;

    .search-input-container {
      display: flex;
      align-items: center;
      background: #f5f5f5;
      /* border-radius: 8px;
      padding: 0.5rem 1rem; */
      margin-bottom: 1.5rem;
      height: 40px;
      padding: 0 1rem;
      border-radius: 1.5rem;

      .search-input-mobile {
        flex: 1;
        border: none;
        background: transparent;
        outline: none;
        font-size: 1rem;
        padding: 0.5rem 0;
      }

      .search-button-mobile {
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
        display: flex;
      }
    }

    .trending-searches {
      margin-bottom: 2rem;

      h3 {
        font-size: 1.1rem;
        margin-bottom: 1rem;
        color: #333;
      }

      .search-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;

        .search-tag {
          background: #f5f5f5;
          padding: 0.5rem 1rem;
          border-radius: 20px;
          font-size: 0.9rem;
          color: #333;
        }
      }
    }

    .top-downloads {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;

        h3 {
          font-size: 1.1rem;
          color: #333;
        }

        .see-all {
          color: #666;
          text-decoration: none;
          font-size: 0.8rem;
          display: flex;
          align-items: center;
          .el-icon {
            width: .8rem;
            width: .8rem;
          }
        }
      }

      .app-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1rem;

        .app-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          text-decoration: none;

          img {
            width: 64px;
            height: 64px;
            border-radius: 12px;
            margin-bottom: 0.5rem;
          }

          .app-info {
            .app-name {
              font-size: 0.9rem;
              color: #333;
              margin-bottom: 0.25rem;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              max-width: 100px;
            }

            .app-rating {
              font-size: 0.8rem;
              color: #F75867;
              display: flex;
              justify-content: center;
              gap: .2rem;
              .icon {
                color: #666;
              }
            }
          }
        }
      }
    }
  }
}
</style>
